//
//  HomeViewController.m
//  DaiShengInvest
//
//  Created by 张睿 on 2017/6/27.
//  Copyright © 2017年 davinci. All rights reserved.
//

#import "HomeViewController.h"
#import "AppDelegate.h"
#import "BlackNavViewController.h"
#import "LoginViewController.h"
#import "HomeView.h"
#import "HistoryOrderViewController.h"
#import "ChooseProductViewController.h"
#import "PendingOrderController.h"
#import "TransactionRulesViewController.h"
#import "ChangeViewController.h"
#import "NowPositionViewController.h"
#import "MessageVerifyViewController.h"
#import "OrderViewController.h"
#import "LandscapeViewController.h"
#import "YKLineChart2.h"
#import <SocketRocket.h>
#import "PayViewController.h"
#import "MoneyCardViewController.h"
#import "PendingInfoViewController.h"
#import "OrderInfoViewController.h"
#import "UIView+Frame.h"


@interface HomeViewController ()<SRWebSocketDelegate>

@property (nonatomic, strong)HomeView * homeView;

@property (nonatomic, strong)SRWebSocket * webSocket;

@property (nonatomic, strong)SRWebSocket * webSocketNumber;

@property (strong, nonatomic) YKLineChartView2 *klineView;

@property (nonatomic, copy)NSString * buttonString;

@property (nonatomic, strong)UIView * bottomView;
@property (nonatomic, strong)UIButton * m1Button;
@property (nonatomic, strong)UIButton * m5Button;
@property (nonatomic, strong)UIButton * m15Button;
@property (nonatomic, strong)UIButton * m30Button;
@property (nonatomic, strong)UIButton * h1Button;
@property (nonatomic, strong)UIButton * h4Button;
@property (nonatomic, strong)UIButton * d1Button;
@property (nonatomic, strong)UIButton * w1Button;
@property (nonatomic, strong)UIButton * mn1Button;


@property (nonatomic, strong)UITextField * pendingTextField;

@property (nonatomic, weak)UIButton * addButton;

@property (nonatomic, weak)UIButton * reduceButton;


@property (nonatomic, weak)UIImageView * sellImageButton;

@property (nonatomic, weak)UILabel * sellCountLabel;

@property (nonatomic, weak)UILabel * buyCountLabel;

@property (nonatomic, weak)UIImageView * buyImageButton;


@property (nonatomic, copy)NSString * userID;

//是否持仓单  0,1
@property (nonatomic, copy)NSString * isPositions;

@property (nonatomic, copy)NSString * orderId;

@property (nonatomic, copy)NSString * positionId;

//@property (nonatomic, assign)float high;
//@property (nonatomic, assign)float low;

@property (nonatomic, weak)UIView * lineView;

@property (nonatomic, strong)NSTimer * countDownTimer;

@property (nonatomic, copy)NSString * request;

@property (nonatomic, weak)UILabel * nowPriceLabel;
@property (nonatomic, weak)UILabel * higestLabel;
@property (nonatomic, weak)UILabel * higestValueLabel;
@property (nonatomic, weak)UILabel * lowestLabel;
@property (nonatomic, weak)UILabel * lowestValueLabel;

@property (nonatomic, strong)NSArray * fiveArray;
@property (nonatomic, strong)NSArray * threeArray;
@property (nonatomic, strong)NSArray * twoArray;

@property (nonatomic, weak)UIView * topView;

@end

@implementation HomeViewController

//倒计时总的秒数
static NSInteger  secondsCountDown = 2;


- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    
//    NSLog(@"=========haaha");
    
    self.orderId = @"";
    
    [self loadKlineData];
    [self loadData];
    
    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
    
    self.userID = [userDefaults objectForKey:@"userId"];
    
    if (self.userID) {
        
        [self loadTopViewData];
        [self loadTopView];
    }
    
    self.view.autoresizingMask = UIViewAutoresizingNone;
    [self interfaceOrientation:UIInterfaceOrientationPortrait];
    
    [self setupDownTimer];
}


- (void)setupDownTimer{
    
    _countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countDownAction) userInfo:nil repeats:YES];
}


//定时器的方法
- (void)countDownAction{
    
    secondsCountDown --;
    
    //当倒计时到0时做需要的操作，button变成可选状态
    if(secondsCountDown == 0){
        
        [_countDownTimer invalidate];
        
        [[NetworkTool sharedTools] POST:@"user/user-info" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
            
            NSDictionary * dict = responseObject[@"param"];
            
            float userMoneyString = [dict[@"marginFree"] floatValue];
            
            self.homeView.traderMoneyString  = [NSString stringWithFormat:@"$%.2f",userMoneyString];
            self.homeView.canUseEnsureString = [NSString stringWithFormat:@"$%.2f",userMoneyString];
            
            secondsCountDown = 2;
            
            [self setupDownTimer];
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            
        }];
    }
}


//强制竖屏
- (void)interfaceOrientation:(UIInterfaceOrientation)orientation
{
    if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
        SEL selector  = NSSelectorFromString(@"setOrientation:");
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
        [invocation setSelector:selector];
        [invocation setTarget:[UIDevice currentDevice]];
        int val = orientation;
        // 从2开始是因为0 1 两个参数已经被selector和target占用
        [invocation setArgument:&val atIndex:2];
        [invocation invoke];
    }
}


- (void)loadKlineData{
    
//    NSLog(@"=========xixi");
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    NSString * startStr;
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    //设置时区,这个对于时间的处理有时很重要
    
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    
    [formatter setTimeZone:timeZone];
    
    NSDate *datenow = [NSDate date];//现在时间
    
    //时间转时间戳的方法:
    
    NSInteger timeSp = [[NSNumber numberWithDouble:[datenow timeIntervalSince1970]] integerValue];
    
    if ([self.buttonString isEqualToString:@"m1"]) {
        
        NSString * isSunday = [self weekdayStringFromDate:datenow];
        
        NSInteger startTime = 0;
        
        if ([isSunday isEqualToString:@"Sunday"]) {
            startTime = timeSp - 2 * 24 * 3600;
        }else{
            startTime = timeSp - 1 * 24 * 3600;
        }
        
        //            NSInteger startTime = timeSp - 2 * 24 * 3600;
        
        NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:startTime];
        
        NSString *confromTimespStr = [formatter stringFromDate:confromTimesp];
        
        
        NSArray *array = [confromTimespStr componentsSeparatedByString:@" "]; //从字符A中分隔成2个元素的数组
        
        startStr = [NSString stringWithFormat:@"%@T%@Z",array.firstObject,array.lastObject];
        
    }else if ([self.buttonString isEqualToString:@"m5"]){
        
        NSInteger startTime = timeSp - 5 * 24 * 3600;
        
        NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:startTime];
        
        NSString *confromTimespStr = [formatter stringFromDate:confromTimesp];
        
        
        NSArray *array = [confromTimespStr componentsSeparatedByString:@" "]; //从字符A中分隔成2个元素的数组
        
        startStr = [NSString stringWithFormat:@"%@T%@Z",array.firstObject,array.lastObject];
        
    }else if ([self.buttonString isEqualToString:@"m15"]){
        
        NSInteger startTime = timeSp - 15 * 24 * 3600;
        
        NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:startTime];
        
        NSString *confromTimespStr = [formatter stringFromDate:confromTimesp];
        
        
        NSArray *array = [confromTimespStr componentsSeparatedByString:@" "]; //从字符A中分隔成2个元素的数组
        
        startStr = [NSString stringWithFormat:@"%@T%@Z",array.firstObject,array.lastObject];
        
    }else if ([self.buttonString isEqualToString:@"m30"]){
        
        NSInteger startTime = timeSp - 30 * 24 * 3600;
        
        NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:startTime];
        
        NSString *confromTimespStr = [formatter stringFromDate:confromTimesp];
        
        
        NSArray *array = [confromTimespStr componentsSeparatedByString:@" "]; //从字符A中分隔成2个元素的数组
        
        startStr = [NSString stringWithFormat:@"%@T%@Z",array.firstObject,array.lastObject];
        
    }else if ([self.buttonString isEqualToString:@"h1"]){
        
        NSInteger startTime = timeSp - 60 * 24 * 3600;
        
        NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:startTime];
        
        NSString *confromTimespStr = [formatter stringFromDate:confromTimesp];
        
        
        NSArray *array = [confromTimespStr componentsSeparatedByString:@" "]; //从字符A中分隔成2个元素的数组
        
        startStr = [NSString stringWithFormat:@"%@T%@Z",array.firstObject,array.lastObject];
        
    }else if ([self.buttonString isEqualToString:@"h4"]){
        
        NSInteger startTime = timeSp - 240 * 24 * 3600;
        
        NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:startTime];
        
        NSString *confromTimespStr = [formatter stringFromDate:confromTimesp];
        
        
        NSArray *array = [confromTimespStr componentsSeparatedByString:@" "]; //从字符A中分隔成2个元素的数组
        
        startStr = [NSString stringWithFormat:@"%@T%@Z",array.firstObject,array.lastObject];
        
    }else if ([self.buttonString isEqualToString:@"w1"]){
        
        NSInteger startTime = timeSp - 10080 * 24 * 3600;
        
        NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:startTime];
        
        NSString *confromTimespStr = [formatter stringFromDate:confromTimesp];
        
        
        NSArray *array = [confromTimespStr componentsSeparatedByString:@" "]; //从字符A中分隔成2个元素的数组
        
        startStr = [NSString stringWithFormat:@"%@T%@Z",array.firstObject,array.lastObject];
        
    }else{
        
        NSInteger startTime = timeSp * 0.3;
        
        NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:startTime];
        
        NSString *confromTimespStr = [formatter stringFromDate:confromTimesp];
        
        
        NSArray *array = [confromTimespStr componentsSeparatedByString:@" "]; //从字符A中分隔成2个元素的数组
        
        startStr = [NSString stringWithFormat:@"%@T%@Z",array.firstObject,array.lastObject];
        
    }
    
//    NSString * sting = [];
    
    NSDictionary * parameters = @{@"period":self.buttonString,@"symbol":self.request,@"startTime":startStr};
    
    
    [[NetworkTool sharedTools] POST:@"symbols/charts" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
        
//        NSLog(@"==%@",responseObject);
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        
        
        
        NSString * countype;
        BOOL isFivebool = [self.fiveArray containsObject: self.request];
        BOOL isThreebool = [self.threeArray containsObject: self.request];
        BOOL isTwobool = [self.twoArray containsObject: self.request];
        
        if (isFivebool) {
            countype = @"five";
        }
        
        if (isThreebool) {
            countype = @"three";
        }
        
        if (isTwobool) {
            countype = @"two";
        }
        
        NSDictionary * dict = responseObject[@"param"];
        NSArray * sourceArray = dict[@"list"];
        
        NSMutableArray * array = [NSMutableArray array];
        for (NSDictionary * dic in sourceArray) {
            
            YKLineEntity2 * entity = [[YKLineEntity2 alloc]init];
            
            entity.high = [dic[@"high"] doubleValue] * 10000;
        
            entity.open = [dic[@"open"] doubleValue] * 10000;
            
//            if (entity.high > self.high) {
//                self.high = entity.high / 10000;
//            }
            
            entity.low = [dic[@"low"] doubleValue] * 10000;
            
            entity.close = [dic[@"close"] doubleValue] * 10000;
            
//            if (entity.low < self.low) {
//                self.low = entity.low / 10000;
//            }
            
            NSString *string = [NSString stringWithFormat:@"%@",dic[@"timestamp"]];//model.modifyTime;
            NSTimeInterval second = string.longLongValue;
            
            
            // 时间戳 -> NSDate *
            NSDateFormatter *matter = [[NSDateFormatter alloc]init];
            matter.dateFormat =@"MM-dd HH:mm";
            NSDate *date = [NSDate dateWithTimeIntervalSince1970:second];
            NSString*timeStr = [matter stringFromDate:date];
            //        NSLog(@"%@", date);
            
            //        self.timeLabel.text = [NSString stringWithFormat:@"%@",date];
            
            entity.date = [NSString stringWithFormat:@"%@", timeStr];//dic[@"date"];
            entity.ma5 = 0;//[dic[@"avg5"] doubleValue];
            entity.ma10 = 0;//[dic[@"avg10"] doubleValue];
            entity.ma20 = 0;//[dic[@"avg20"] doubleValue];
            entity.volume = 0;//[dic[@"volume"] doubleValue] * 10000;//[dic[@"total_volume_trade"] doubleValue];
            [array addObject:entity];
            //YTimeLineEntity * entity = [[YTimeLineEntity alloc]init];
        }
        //        [array addObjectsFromArray:array];
        
        
        
        YKLineDataSet2 * dataset = [[YKLineDataSet2 alloc]init];
        dataset.data = array;
        dataset.highlightLineColor = [UIColor whiteColor];//[UIColor colorWithRed:60/255.0 green:76/255.0 blue:109/255.0 alpha:1.0];
        dataset.highlightLineWidth = 0.7;
        dataset.candleRiseColor = [UIColor colorWithRed:233/255.0 green:47/255.0 blue:68/255.0 alpha:1.0];
        dataset.candleFallColor = [UIColor colorWithRed:33/255.0 green:179/255.0 blue:77/255.0 alpha:1.0];
        dataset.avgLineWidth = 1.f;
        dataset.avgMA10Color = [UIColor colorWithRed:252/255.0 green:85/255.0 blue:198/255.0 alpha:1.0];
        dataset.avgMA5Color = [UIColor colorWithRed:67/255.0 green:85/255.0 blue:109/255.0 alpha:1.0];
        dataset.avgMA20Color = [UIColor colorWithRed:216/255.0 green:192/255.0 blue:44/255.0 alpha:1.0];
        dataset.candleTopBottmLineWidth = 1;
        
        
        self.klineView = [[YKLineChartView2 alloc] initWithFrame:CGRectMake(0, 164 * SCREENH6, SCREEN_WIDTH, 267 * SCREENH6)];
        [self.view addSubview:self.klineView];
        
        [self.klineView setupChartOffsetWithLeft:50 top:50 right:0 bottom:-20];
        self.klineView.gridBackgroundColor = ColorWithRGB(0x242424);
        self.klineView.borderColor = [UIColor colorWithRed:203/255.0 green:215/255.0 blue:224/255.0 alpha:1.0];
        self.klineView.borderWidth = .5;
        self.klineView.candleWidth = 8;
        self.klineView.candleMaxWidth = 30;
        self.klineView.candleMinWidth = 7;
        self.klineView.uperChartHeightScale = 0.7;
        self.klineView.xAxisHeitht = 25;
        //        self.klineView.delegate = self;
        self.klineView.highlightLineShowEnabled = YES;
        self.klineView.zoomEnabled = YES;
        self.klineView.scrollEnabled = YES;
        self.klineView.type = @"home";
        self.klineView.countType = countype;
        [self.klineView setupData:dataset];
        
//        NSLog(@"==%f",self.high);
//        NSLog(@"==%f",self.low);
        
        //    [self setupButtomView];
        self.bottomView.hidden = NO;
        self.topView.hidden = NO;
        //下面这段代码是 将bottomView调整到父视图的最上面
        [self.view bringSubviewToFront:self.bottomView];
        [self.view bringSubviewToFront:self.topView];
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"%@",error);
    }];
}


- (void)setupTopView{
    
    UIView * topView = [[UIView alloc] initWithFrame:CGRectMake(0, 170 * SCREENH6, SCREEN_WIDTH, 40 * SCREENH6)];
    
    topView.backgroundColor = [UIColor clearColor];
    topView.hidden = YES;
    
    self.topView = topView;
    
    [self.view addSubview:self.topView];
    
    
    UIButton * presentButton = [[UIButton alloc] initWithFrame:CGRectMake(333 * SCREENH6, 0 , 40 * SCREENH6, 40 * SCREENH6)];
    
    [presentButton setBackgroundColor:[UIColor clearColor]];
    //    [presentButton setTitle:@"did" forState:UIControlStateNormal];
    [presentButton setImage:[UIImage imageNamed:@"横屏转竖屏"] forState:UIControlStateNormal];
    [presentButton addTarget:self action:@selector(didShowLandscape) forControlEvents:UIControlEventTouchUpInside];
    
    [self.topView addSubview:presentButton];
    
    [self.view bringSubviewToFront:presentButton];
    
    UILabel * nowPriceLabel = [UILabel new];
    
    nowPriceLabel.textColor = [UIColor whiteColor];
    nowPriceLabel.font = [UIFont systemFontOfSize:20 * SCREENH6];
    nowPriceLabel.text = @"----";
    
    self.nowPriceLabel = nowPriceLabel;
    
    [self.topView addSubview:self.nowPriceLabel];
    
    [self.nowPriceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.topView).offset(15 * SCREENH6);
        make.centerY.mas_equalTo(presentButton);
    }];
    
    UILabel * higestLabel = [UILabel new];
    
    higestLabel.textColor = ColorWithRGB(0x8d8d8d);
    //        higestLabel.backgroundColor = [UIColor redColor];
    higestLabel.font = [UIFont systemFontOfSize:12 * SCREENH6];
    higestLabel.text = @"最高:";
    
    self.higestLabel = higestLabel;
    
    [self.topView addSubview:self.higestLabel];
    
    [self.higestLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.nowPriceLabel.mas_trailing).offset(20 * SCREENH6);
        make.top.mas_equalTo(presentButton).offset(5 * SCREENH6);
    }];
    
    UILabel * higestValueLabel = [UILabel new];
    
    higestValueLabel.textColor = ColorWithRGB(0x8d8d8d);
    higestValueLabel.font = [UIFont systemFontOfSize:12 * SCREENH6];
    higestValueLabel.text = @"----";
    
    self.higestValueLabel = higestValueLabel;
    
    [self.topView addSubview:self.higestValueLabel];
    
    [self.higestValueLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading. mas_equalTo(self.higestLabel.mas_trailing).offset(5 * SCREENH6);
        make.centerY.mas_equalTo(self.higestLabel);
    }];
    
    
    UILabel * lowestLabel = [UILabel new];
    
    lowestLabel.textColor = ColorWithRGB(0x8d8d8d);
    lowestLabel.font = [UIFont systemFontOfSize:12 * SCREENH6];
    lowestLabel.text = @"最低:";
    
    self.lowestLabel = lowestLabel;
    
    [self.topView addSubview:self.lowestLabel];
    
    [self.lowestLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading. mas_equalTo(self.higestLabel);
        make.top.mas_equalTo(self.higestLabel.mas_bottom).offset(3 * SCREENH6);
    }];
    
    UILabel * lowestValueLabel = [UILabel new];
    
    lowestValueLabel.textColor = ColorWithRGB(0x8d8d8d);
    lowestValueLabel.font = [UIFont systemFontOfSize:12 * SCREENH6];
    lowestValueLabel.text = @"----";
    
    self.lowestValueLabel = lowestValueLabel;
    
    [self.topView addSubview:self.lowestValueLabel];
    
    [self.lowestValueLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading. mas_equalTo(self.higestValueLabel);
        make.centerY.mas_equalTo(self.lowestLabel);
    }];
    
    
    
}

- (void)loadTopView{
 
    NSDictionary * parameters = @{@"symbol":self.request};
    
    [[NetworkTool sharedTools] POST:@"symbols/detail" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
        
//        NSLog(@"==%@",responseObject);
        
        
        NSString * code = [NSString stringWithFormat:@"%@",responseObject[@"code"]];
        
        if ([code isEqualToString:@"0"]) {
            
            NSDictionary * paramDict = responseObject[@"param"];
            
            NSDictionary * dict = paramDict[@"data"];
            self.positionId = dict[@"positionId"];
            
            NSString * ishas = [NSString stringWithFormat:@"%@",paramDict[@"isHas"]];
            self.isPositions = [NSString stringWithFormat:@"%@",paramDict[@"isPositions"]];
            
            if ([ishas isEqualToString:@"0"]) {
                //没有持仓
                self.homeView.changeButtonImage = @"入金";
            }else{
                self.homeView.changeButtonImage = @"全平";
                //            NSDictionary * data = paramDict[@"data"];
                //
                //            self.orderId = [NSString stringWithFormat:@"%@",data[@"orderId"]];
                
                //            NSLog(@"==%@",self.orderId);
            }
        }
        
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"%@",error);
    }];
 
    
}

- (void)loadTopViewData{
    
    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
    
    NSString * userID = [NSString stringWithFormat:@"%@",[userDefaults objectForKey:@"userId"]];
//    NSLog(@"==%@",userID);
    NSString * lastLoginTimeStr = [NSString stringWithFormat:@"%@",[userDefaults objectForKey:@"lastLoginTime"]];
//    NSLog(@"==%@",lastLoginTimeStr);
    NSString * createTimeStr = [NSString stringWithFormat:@"%@",[userDefaults objectForKey:@"createTime"]];
//    NSLog(@"==%@",createTimeStr);
    
    [NetworkTool sharedTools].responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/html", @"image/jpeg",@"image/png", @"application/octet-stream", nil];
    
    [NetworkTool sharedTools].requestSerializer = [AFHTTPRequestSerializer serializer];
    
    [[NetworkTool sharedTools].requestSerializer setValue:createTimeStr forHTTPHeaderField:@"createTime"];
    [[NetworkTool sharedTools].requestSerializer setValue:lastLoginTimeStr forHTTPHeaderField:@"lastLoginTime"];
    [[NetworkTool sharedTools].requestSerializer setValue:userID forHTTPHeaderField:@"userId"];

    
    [[NetworkTool sharedTools] POST:@"user/user-info" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
        
//        NSLog(@"==%@",responseObject);
        
        NSDictionary * dict = responseObject[@"param"];
        //用户信息
        
        if(dict){
            
            NSDictionary * otherInfoDict = dict[@"otherInfo"];
            
            //账户余额
            float balanceFloat = [dict[@"balance"] floatValue];
            NSString * balanceFloatString = [NSString stringWithFormat:@"$%.2f",balanceFloat];
            //浮动盈亏
            NSString * floatProfitString;
            float floatProfit = [dict[@"floatProfit"] floatValue];
            
            if (floatProfit >= 0) {
                floatProfitString = [NSString stringWithFormat:@"+$%.2f",floatProfit];
            }else{

                NSString * floatString = [NSString stringWithFormat:@"%.2f",floatProfit];
                floatString = [floatString substringFromIndex:1];
                
                floatProfitString = [NSString stringWithFormat:@"-$%@",floatString];
            }
            
//            NSString * floatProfitString = [NSString stringWithFormat:@"%.2f",floatProfit];
            //可用保证金
            float marginFree = [dict[@"marginFree"] floatValue];
            //净值
            float clearMoney = balanceFloat + floatProfit;
            NSString * clearMoneyString = [NSString stringWithFormat:@"$%.2f",clearMoney];
            //可用资金    已用保证金
            
            NSString * canUseMoneyString = [NSString stringWithFormat:@"%.2f",marginFree];
//            float canUseMoney = clearMoney - marginFree;
//            
//            float useMoney =  balanceFloat - canUseMoney + floatProfit;
//            
//            NSString * canUseMoneyString = [NSString stringWithFormat:@"$%.2f",useMoney];
            
            self.homeView.traderMoneyString = canUseMoneyString;//dict[@"cashAvailable"];
            self.homeView.canUseEnsureString = canUseMoneyString;
            //用户信息
            NSString * nickName = [NSString stringWithFormat:@"%@",otherInfoDict[@"nickname"]];
            
            if ([nickName isEqualToString:@""]) {
                nickName = [NSString stringWithFormat:@"%@",otherInfoDict[@"phone"]];
            }
            NSString * iconUrl = [NSString stringWithFormat:@"%@",otherInfoDict[@"avatar"]];
            
            NSString * emailString = [NSString stringWithFormat:@"%@",otherInfoDict[@"email"]];
            
            NSString * phone = [NSString stringWithFormat:@"%@",otherInfoDict[@"phone"]];
            
            NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
            
            [userDefaults setObject:balanceFloatString forKey:@"balance"];
            [userDefaults setObject:floatProfitString forKey:@"floatProfit"];
            [userDefaults setObject:clearMoneyString forKey:@"clearMoney"];
            [userDefaults setObject:canUseMoneyString forKey:@"canUseMoney"];
            [userDefaults setObject:nickName forKey:@"nickNameString"];
            [userDefaults setObject:iconUrl forKey:@"iconUrl"];
            [userDefaults setObject:emailString forKey:@"emailString"];
            [userDefaults setObject:phone forKey:@"phone"];
            
            [userDefaults synchronize];
        }
        
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"%@",error);
    }];
    
}




- (void)loadData{
    
//    _webSocket.delegate = nil;
//    [_webSocket close];
//    
////    _webSocket = [[SRWebSocket alloc] initWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"ws://101.37.78.116:9505"]]];
//    //03.20.249.35
//    _webSocket = [[SRWebSocket alloc] initWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"ws://103.20.249.35:9505"]]];
//    
//    _webSocket.delegate = self;
//    
////    NSOperationQueue *operation = [NSBlockOperation blockOperationWithBlock:^{
////        NSLog(@"%@", [NSThread currentThread]);
////    }];
////    [_webSocket setDelegateOperationQueue:[NSOperationQueue new]];
//    
//    [_webSocket open];

    
    _webSocketNumber.delegate = nil;
    [_webSocketNumber close];
    
    _webSocketNumber = [[SRWebSocket alloc] initWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"ws://103.20.249.35:9506"]]];
    
//    NSOperationQueue * que = [NSOperationQueue new];
    _webSocketNumber.delegate = self;
//    [_webSocketNumber setDelegateDispatchQueue:queue];
//    [_webSocketNumber setDelegateOperationQueue:[NSOperationQueue mainQueue]];
    [_webSocketNumber open];

}



- (void)setupButtomView{
    //390
    self.bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, 405 * SCREENH6, SCREEN_WIDTH, 25 * SCREENH6)];
    
    self.bottomView.backgroundColor = ColorWithRGB(0x242424);
    self.bottomView.userInteractionEnabled = YES;
    self.bottomView.hidden = YES;
    
    [self.view addSubview:self.bottomView];
    
    //下面这段代码是 将bottomView调整到父视图的最上面
    [self.view bringSubviewToFront:self.bottomView];
    
    float y = 5 * SCREENH6;
    float x = 10 * SCREENH6;
    float icoW = 35 * SCREENH6;//40;
    //    float icoH = 10 * SCREENH6;//65;
    float spliW = 5 * SCREENH6;
    
    self.m1Button = [[UIButton alloc] initWithFrame:CGRectMake(x, y, icoW, spliW)];
    
    self.m1Button.selected = YES;
    [self.m1Button setTitle:@"1分钟" forState:UIControlStateNormal];
    self.m1Button.titleLabel.font = [UIFont systemFontOfSize:10 * SCREENH6];
    [self.m1Button setTitleColor:ColorWithRGB(0x8d8d8d) forState:UIControlStateNormal];
    [self.m1Button setTitleColor:ColorWithRGB(0xffffff) forState:UIControlStateSelected];
    [self.m1Button addTarget:self action:@selector(UesrClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.bottomView addSubview:self.m1Button];
    
    x += icoW+spliW;
    
    self.m5Button = [[UIButton alloc] initWithFrame:CGRectMake(x, y, icoW, spliW)];
    
    self.m5Button.selected = NO;
    [self.m5Button setTitle:@"5分钟" forState:UIControlStateNormal];
    self.m5Button.titleLabel.font = [UIFont systemFontOfSize:10 * SCREENH6];
    [self.m5Button setTitleColor:ColorWithRGB(0x8d8d8d) forState:UIControlStateNormal];
    [self.m5Button setTitleColor:ColorWithRGB(0xffffff) forState:UIControlStateSelected];
    [self.m5Button addTarget:self action:@selector(UesrClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.bottomView addSubview:self.m5Button];
    
    x += icoW+spliW;
    
    self.m15Button = [[UIButton alloc] initWithFrame:CGRectMake(x, y, icoW, spliW)];
    
    self.m15Button.selected = NO;
    [self.m15Button setTitle:@"15分钟" forState:UIControlStateNormal];
    self.m15Button.titleLabel.font = [UIFont systemFontOfSize:10 * SCREENH6];
    [self.m15Button setTitleColor:ColorWithRGB(0x8d8d8d) forState:UIControlStateNormal];
    [self.m15Button setTitleColor:ColorWithRGB(0xffffff) forState:UIControlStateSelected];
    [self.m15Button addTarget:self action:@selector(UesrClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.bottomView addSubview:self.m15Button];
    
    x += icoW+spliW;
    
    self.m30Button = [[UIButton alloc] initWithFrame:CGRectMake(x, y, icoW, spliW)];
    
    self.m30Button.selected = NO;
    [self.m30Button setTitle:@"30分钟" forState:UIControlStateNormal];
    self.m30Button.titleLabel.font = [UIFont systemFontOfSize:10 * SCREENH6];
    [self.m30Button setTitleColor:ColorWithRGB(0x8d8d8d) forState:UIControlStateNormal];
    [self.m30Button setTitleColor:ColorWithRGB(0xffffff) forState:UIControlStateSelected];
    [self.m30Button addTarget:self action:@selector(UesrClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.bottomView addSubview:self.m30Button];
    
    
    x += icoW+spliW;
    
    self.h1Button = [[UIButton alloc] initWithFrame:CGRectMake(x, y, icoW, spliW)];
    
    self.h1Button.selected = NO;
    [self.h1Button setTitle:@"1小时" forState:UIControlStateNormal];
    self.h1Button.titleLabel.font = [UIFont systemFontOfSize:10 * SCREENH6];
    [self.h1Button setTitleColor:ColorWithRGB(0x8d8d8d) forState:UIControlStateNormal];
    [self.h1Button setTitleColor:ColorWithRGB(0xffffff) forState:UIControlStateSelected];
    [self.h1Button addTarget:self action:@selector(UesrClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.bottomView addSubview:self.h1Button];
    
    x += icoW+spliW;
    
    self.h4Button = [[UIButton alloc] initWithFrame:CGRectMake(x, y, icoW, spliW)];
    
    self.h4Button.selected = NO;
    [self.h4Button setTitle:@"4小时" forState:UIControlStateNormal];
    self.h4Button.titleLabel.font = [UIFont systemFontOfSize:10 * SCREENH6];
    [self.h4Button setTitleColor:ColorWithRGB(0x8d8d8d) forState:UIControlStateNormal];
    [self.h4Button setTitleColor:ColorWithRGB(0xffffff) forState:UIControlStateSelected];
    [self.h4Button addTarget:self action:@selector(UesrClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.bottomView addSubview:self.h4Button];
    
    
    x += icoW+spliW;
    
    self.d1Button = [[UIButton alloc] initWithFrame:CGRectMake(x, y, icoW, spliW)];
    
    self.d1Button.selected = NO;
    [self.d1Button setTitle:@"1天" forState:UIControlStateNormal];
    self.d1Button.titleLabel.font = [UIFont systemFontOfSize:10 * SCREENH6];
    [self.d1Button setTitleColor:ColorWithRGB(0x8d8d8d) forState:UIControlStateNormal];
    [self.d1Button setTitleColor:ColorWithRGB(0xffffff) forState:UIControlStateSelected];
    [self.d1Button addTarget:self action:@selector(UesrClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.bottomView addSubview:self.d1Button];
    
    x += icoW+spliW;
    
    self.w1Button = [[UIButton alloc] initWithFrame:CGRectMake(x, y, icoW, spliW)];
    
    self.w1Button.selected = NO;
    [self.w1Button setTitle:@"1周" forState:UIControlStateNormal];
    self.w1Button.titleLabel.font = [UIFont systemFontOfSize:10 * SCREENH6];
    [self.w1Button setTitleColor:ColorWithRGB(0x8d8d8d) forState:UIControlStateNormal];
    [self.w1Button setTitleColor:ColorWithRGB(0xffffff) forState:UIControlStateSelected];
    [self.w1Button addTarget:self action:@selector(UesrClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.bottomView addSubview:self.w1Button];
    
    x += icoW+spliW;
    
    self.mn1Button = [[UIButton alloc] initWithFrame:CGRectMake(x, y, icoW, spliW)];
    
    self.mn1Button.selected = NO;
    [self.mn1Button setTitle:@"1月" forState:UIControlStateNormal];
    self.mn1Button.titleLabel.font = [UIFont systemFontOfSize:10 * SCREENH6];
    [self.mn1Button setTitleColor:ColorWithRGB(0x8d8d8d) forState:UIControlStateNormal];
    [self.mn1Button setTitleColor:ColorWithRGB(0xffffff) forState:UIControlStateSelected];
    [self.mn1Button addTarget:self action:@selector(UesrClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.bottomView addSubview:self.mn1Button];
}

- (void)webSocketDidOpen:(SRWebSocket *)webSocket;
{
    NSLog(@"Websocket Connected");
    
}

- (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error;
{
    NSLog(@":( Websocket Failed With Error %@", error);
    
    _webSocket = nil;
}


- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message;
{
    
    
    NSData *jsonData = [message dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    
    NSArray * array = dic[@"quote"];
    
    
    for (NSDictionary * productInfoDict in array) {
        
        NSString * name = [NSString stringWithFormat:@"%@",productInfoDict[@"symbol"]];
        
        if ([self.request isEqualToString:name]) {
            
            NSString * bid = [NSString stringWithFormat:@"%@",productInfoDict[@"bid"]];
            NSString * ask = [NSString stringWithFormat:@"%@",productInfoDict[@"ask"]];
            float bidFloat = [bid floatValue];
            float high = [productInfoDict[@"high"] floatValue];
            float low = [productInfoDict[@"low"] floatValue];
            
            self.sellCountLabel.text = bid;
            self.buyCountLabel.text = ask;
            self.klineView.nowPrice = bidFloat;
            BOOL isFivebool = [self.fiveArray containsObject:self.request];
            BOOL isThreebool = [self.threeArray containsObject:self.request];
            BOOL isTwobool = [self.twoArray containsObject:self.request];
            
            if (isFivebool) {
                
                self.nowPriceLabel.text = [NSString stringWithFormat:@"%.5f",bidFloat];
                self.higestValueLabel.text = [NSString stringWithFormat:@"%.5f",high];
                self.lowestValueLabel.text = [NSString stringWithFormat:@"%.5f",low];
            }
            
            if (isThreebool) {
                
                self.nowPriceLabel.text = [NSString stringWithFormat:@"%.3f",bidFloat];
                self.higestValueLabel.text = [NSString stringWithFormat:@"%.3f",high];
                self.lowestValueLabel.text = [NSString stringWithFormat:@"%.3f",low];
            }
            
            if (isTwobool) {
                
                self.nowPriceLabel.text = [NSString stringWithFormat:@"%.2f",bidFloat];
                self.higestValueLabel.text = [NSString stringWithFormat:@"%.2f",high];
                self.lowestValueLabel.text = [NSString stringWithFormat:@"%.2f",low];
            }
            
            
            
        }
    }
    
}


- (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean;
{
    NSLog(@"WebSocket closed");
    _webSocket = nil;
}

- (void)webSocket:(SRWebSocket *)webSocket didReceivePong:(NSData *)pongPayload;
{
    NSLog(@"Websocket received pong");
}

-(void)chartValueSelected:(YKViewBase2 *)chartView entry:(id)entry entryIndex:(NSInteger)entryIndex
{
    
}

- (void)chartValueNothingSelected:(YKViewBase2 *)chartView
{
    
}

- (void)UesrClicked:(UIButton *)button{
    
    if (button == self.m1Button) {
        
        self.m1Button.selected = YES;
        
        self.m5Button.selected = NO;
        self.m15Button.selected = NO;
        self.m30Button.selected = NO;
        self.h1Button.selected = NO;
        self.h4Button.selected = NO;
        self.d1Button.selected = NO;
        self.w1Button.selected = NO;
        self.mn1Button.selected = NO;
        
        self.buttonString = @"m1";
        
        [self loadKlineData];
        [self loadData];
        
    }else if (button == self.m5Button){
        
        self.m5Button.selected = YES;
        
        self.m1Button.selected = NO;
        self.m15Button.selected = NO;
        self.m30Button.selected = NO;
        self.h1Button.selected = NO;
        self.h4Button.selected = NO;
        self.d1Button.selected = NO;
        self.w1Button.selected = NO;
        self.mn1Button.selected = NO;
        
        self.buttonString = @"m5";
        
        [self loadKlineData];
        [self loadData];
        
    }else if (button == self.m15Button){
        
        self.m15Button.selected = YES;
        
        self.m1Button.selected = NO;
        self.m5Button.selected = NO;
        self.m30Button.selected = NO;
        self.h1Button.selected = NO;
        self.h4Button.selected = NO;
        self.d1Button.selected = NO;
        self.w1Button.selected = NO;
        self.mn1Button.selected = NO;
        
        self.buttonString = @"m15";
        
        [self loadKlineData];
        [self loadData];
        
    }else if (button == self.m30Button){
        
        self.m30Button.selected = YES;
        
        self.m1Button.selected = NO;
        self.m5Button.selected = NO;
        self.m15Button.selected = NO;
        self.h1Button.selected = NO;
        self.h4Button.selected = NO;
        self.d1Button.selected = NO;
        self.w1Button.selected = NO;
        self.mn1Button.selected = NO;
        
        self.buttonString = @"m30";
        
        [self loadKlineData];
        [self loadData];
        
    }else if (button == self.h1Button){
        
        self.h1Button.selected = YES;
        
        self.m1Button.selected = NO;
        self.m5Button.selected = NO;
        self.m15Button.selected = NO;
        self.m30Button.selected = NO;
        self.h4Button.selected = NO;
        self.d1Button.selected = NO;
        self.w1Button.selected = NO;
        self.mn1Button.selected = NO;
        
        self.buttonString = @"h1";
        
        [self loadKlineData];
        [self loadData];
        
    }else if (button == self.h4Button){
        
        self.h4Button.selected = YES;
        
        self.m1Button.selected = NO;
        self.m5Button.selected = NO;
        self.m15Button.selected = NO;
        self.m30Button.selected = NO;
        self.h1Button.selected = NO;
        self.d1Button.selected = NO;
        self.w1Button.selected = NO;
        self.mn1Button.selected = NO;
        
        self.buttonString = @"h4";
        
        [self loadKlineData];
        [self loadData];
        
    }else if (button == self.d1Button){
        
        self.d1Button.selected = YES;
        
        self.m1Button.selected = NO;
        self.m5Button.selected = NO;
        self.m15Button.selected = NO;
        self.m30Button.selected = NO;
        self.h1Button.selected = NO;
        self.h4Button.selected = NO;
        self.w1Button.selected = NO;
        self.mn1Button.selected = NO;
        
        self.buttonString = @"d1";
        
        [self loadKlineData];
        [self loadData];
        
    }else if (button == self.w1Button){
        
        self.w1Button.selected = YES;
        
        self.m1Button.selected = NO;
        self.m5Button.selected = NO;
        self.m15Button.selected = NO;
        self.m30Button.selected = NO;
        self.h1Button.selected = NO;
        self.h4Button.selected = NO;
        self.d1Button.selected = NO;
        self.mn1Button.selected = NO;
        
        self.buttonString = @"w1";
        
        [self loadKlineData];
        [self loadData];
        
    }else{
        
        self.mn1Button.selected = YES;
        
        self.m1Button.selected = NO;
        self.m5Button.selected = NO;
        self.m15Button.selected = NO;
        self.m30Button.selected = NO;
        self.h1Button.selected = NO;
        self.h4Button.selected = NO;
        self.d1Button.selected = NO;
        self.w1Button.selected = NO;
        
        self.buttonString = @"mn1";
        
        [self loadKlineData];
        [self loadData];
    }
    
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    self.title = @"交易";
    
    self.navigationItem.title = @"黄金美元(XAUUSDapp)";
    self.request = @"XAUUSDapp";
    self.fiveArray = @[@"EURUSDapp",@"NZDUSDapp",@"EURCADapp",@"USDCADapp",@"EURNZDapp",@"AUDNZDapp",@"AUDUSDapp",@"AUDCADapp",@"GBPCHFapp",@"EURAUDapp",@"EURGBPapp",@"CADCHFapp",@"GBPAUDapp",@"EURCHFapp",@"USDCHFapp",@"GBPCADapp",@"GBPNZDapp",@"AUDCHFapp",@"GBPUSDapp"];
    self.threeArray = @[@"XAGUSDapp",@"GBPJPYapp",@"AUDJPYapp",@"USDJPYapp",@"EURJPYapp",@"CADJPYapp",@"NZDJPYapp"];
    self.twoArray = @[@"XAUUSDapp"];
    
    self.tabBarItem.title = @"交易";
    self.buttonString = @"m1";
    
    
//    [self loadKlineData];
    [self setupTopView];
    [self setupButtomView];
    [self setupNsNotificition];
    [self setupNavVC];
    [self setupUI];
//    [self checkVersions];
}


//- (void)checkVersions{
//    
//    [[NetworkTool sharedTools] POST:@"site/phone" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
//        
////        NSLog(@"==%@",responseObject);
//        
//        NSDictionary * param = responseObject[@"param"];
//        NSDictionary * device = param[@"device"];
//        NSDictionary * iphone = device[@"iphone"];
//        
//        NSString * version = iphone[@"version"];
//        
////        NSLog(@"==%@",version);
//        
//        NSDictionary * info = [NSBundle mainBundle].infoDictionary;
//        NSString * currentVersion = info[@"CFBundleShortVersionString"];
////        NSLog(@"==%@",currentVersion);
//        
//        if ([version isEqualToString:currentVersion]) {
//            
//        }else{
//            
//            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
//                                                                           message:@"有新版请至App Store更新最新版本"
//                                                                    preferredStyle:UIAlertControllerStyleAlert];
//            
//            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
//                                                                  handler:^(UIAlertAction * action) {
//                                                                      //响应事件
////                                                                      NSLog(@"action = %@", action);
//                                                                  }];
//            
//            [alert addAction:defaultAction];
//            [self presentViewController:alert animated:YES completion:nil];
//        }
//        
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        
//    }];
//}


- (void)changeTitleName:(NSNotification *)sender{
    
    self.navigationItem.title = sender.userInfo[@"titleName"];
    self.buyCountLabel.text = sender.userInfo[@"buyString"];
    self.sellCountLabel.text = sender.userInfo[@"sellString"];
    self.request = sender.userInfo[@"requsetString"];
    
//    NSDictionary * parameters = @{@"symbol":self.request};
    
//    [[NetworkTool sharedTools] POST:@"user/balance" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
//        
//        
//        
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        
//        NSLog(@"%@",error);
//    }];
    
//     [self loadKlineData];
}


- (void)setupNavVC{
    
    UIButton * backButton = [[UIButton alloc] init];
    
    backButton.frame = CGRectMake(0 * SCREENH6, 0 * SCREENH6, 22 * SCREENH6, 25 * SCREENH6);
    [backButton setImage:[UIImage imageNamed:@"历史清单"] forState:UIControlStateNormal];
    
    [backButton addTarget:self action:@selector(didWatchHistoryOrder) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem * leftButton = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    self.navigationItem.rightBarButtonItem = leftButton;
    
}


- (void)setupNsNotificition{
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTitleName:) name:@"titleName" object:@"titleString"];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(popToLoginVC) name:@"login" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(popToSetupVC) name:@"setup" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didRightImageButton:) name:@"didImageButton" object:@"buttonTag"];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pushToPendingVC) name:@"pushToPendingVC" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadUserInfo) name:@"loadUserInfo" object:nil];
    
    //注册键盘弹出通知
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    //注册键盘隐藏通知
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];

}


- (void)setupUI{
    
    self.homeView = [[HomeView alloc] initWithFrame:self.view.bounds];
    
    self.homeView.changeButtonImage = @"aaa";
    self.homeView.traderMoneyString = @"0";
    //    self.homeView.noLogin = self.noLogin;
    self.homeView.userInteractionEnabled = YES;
    
    [self.view addSubview:self.homeView];
    
    self.pendingTextField = [self setupTextField:@"交易手数"];
    
    [self.view addSubview:self.pendingTextField];
    
    
    UIImageView * sellImageButton = [UIImageView new];
    
    sellImageButton.image = [UIImage imageNamed:@"卖"];
    sellImageButton.contentMode = UIViewContentModeScaleAspectFill;
    sellImageButton.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapSellGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapSellAction)];
    [sellImageButton addGestureRecognizer:tapSellGR];
    
    self.sellImageButton = sellImageButton;
    
    [self.view addSubview:self.sellImageButton];
    
    UILabel * sellCountLabel = [UILabel new];
    
    sellCountLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:15 * SCREENH6];
    sellCountLabel.textColor = ColorWithRGB(0xffffff);
//    sellCountLabel.text = @"6.78732";
    
    self.sellCountLabel = sellCountLabel;
    
    [self.sellImageButton addSubview:self.sellCountLabel];
    
    
    UIImageView * buyImageButton = [UIImageView new];
    
    buyImageButton.image = [UIImage imageNamed:@"买"];
    buyImageButton.contentMode = UIViewContentModeScaleAspectFill;
    buyImageButton.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapBuyGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapBuyAction)];
    [buyImageButton addGestureRecognizer:tapBuyGR];
    
    self.buyImageButton = buyImageButton;
    
    [self.view addSubview:self.buyImageButton];
    
    UILabel * buyCountLabel = [UILabel new];
    
    buyCountLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:15 * SCREENH6];
    buyCountLabel.textColor = ColorWithRGB(0xffffff);
//    buyCountLabel.text = @"6.78732";
    
    self.buyCountLabel = buyCountLabel;
    
    [self.buyImageButton addSubview:self.buyCountLabel];
    
    
    [self.pendingTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(235 * SCREENH6);
        make.height.mas_equalTo(40 * SCREENH6);
        make.top.mas_equalTo(self.view).offset(482 * SCREENH6);
        make.leading.mas_equalTo(self.view).offset(95 * SCREENH6);
    }];
    
    [self.sellImageButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(47 * SCREENH6);
        make.width.mas_equalTo(145 * SCREENH6);
        make.leading.mas_equalTo(self.view).offset(25 * SCREENH6);
        make.top.mas_equalTo(self.pendingTextField.mas_bottom).offset(43 * SCREENH6);
    }];
    
    [self.sellCountLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.sellImageButton);
        make.leading.mas_equalTo(self.sellImageButton).offset(70 * SCREENH6);
    }];
    
    
    [self.buyImageButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.sellImageButton.mas_trailing).offset(30 * SCREENH6);
        make.width.height.bottom.mas_equalTo(self.sellImageButton);
    }];
    
    [self.buyCountLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.buyImageButton);
        make.leading.mas_equalTo(self.buyImageButton).offset(20 * SCREENH6);
    }];
}


//- (void)viewDidLayoutSubviews{
//    
//    [super viewDidLayoutSubviews];
//    
//    [self.sellImageButton mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.height.mas_equalTo(47 * SCREENH6);
//        make.width.mas_equalTo(145 * SCREENH6);
//        make.leading.mas_equalTo(self.view).offset(25 * SCREENH6);
//        make.bottom.mas_equalTo(self.view).offset(- 8 * SCREENH6);
//    }];
//    
//    [self.sellCountLabel mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.centerY.mas_equalTo(self.sellImageButton);
//        make.leading.mas_equalTo(self.sellImageButton).offset(70 * SCREENH6);
//    }];
//    
//    [self.pendingTextField mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.width.mas_equalTo(235 * SCREENH6);
//        make.height.mas_equalTo(40 * SCREENH6);
//        make.top.mas_equalTo(self.view).offset(482 * SCREENH6);
//        make.leading.mas_equalTo(self.view).offset(95 * SCREENH6);
//    }];
//    
//    
//    [self.buyImageButton mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.leading.mas_equalTo(self.sellImageButton.mas_trailing).offset(30 * SCREENH6);
//        make.width.height.bottom.mas_equalTo(self.sellImageButton);
//    }];
//    
//    [self.buyCountLabel mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.centerY.mas_equalTo(self.buyImageButton);
//        make.leading.mas_equalTo(self.buyImageButton).offset(20 * SCREENH6);
//    }];
//
//}


- (UITextField *)setupTextField:(NSString *)name{
    
    
    UITextField * textFiled = [[UITextField alloc] init];
    
    textFiled.borderStyle = UITextBorderStyleNone;
    textFiled.backgroundColor = [UIColor clearColor];
    
    textFiled.background = [UIImage imageNamed:name];
    textFiled.textAlignment = UITextAlignmentCenter;
    
//    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
//    attrs[NSForegroundColorAttributeName] = ColorWithRGB(0xeeeeee);
//    attrs[NSFontAttributeName] = [UIFont fontWithName:@"PingFangSC-Regular" size:15 * SCREENH6];
//    textFiled.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"0.01" attributes:attrs];
    textFiled.font = [UIFont fontWithName:@"PingFangSC-Regular" size:15 * SCREENH6];
    textFiled.textColor = ColorWithRGB(0xeeeeee);
    textFiled.text = @"0.01";
    
    UIButton * reduceButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40 * SCREENH6, 40 * SCREENH6)];
    
    //    reduceButton.backgroundColor = [UIColor clearColor];
    [reduceButton setImage:[UIImage imageNamed:@"减"] forState:UIControlStateNormal];
    [reduceButton addTarget:self action:@selector(didReduceButton) forControlEvents:UIControlEventTouchUpInside];
    
    
    [textFiled addSubview:reduceButton];
    
    [self.reduceButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(textFiled);
        make.leading.mas_equalTo(textFiled).offset(7 * SCREENH6);
    }];
    
    textFiled.leftView = reduceButton;
    textFiled.leftViewMode = UITextFieldViewModeAlways;
    
    
    UIButton * addButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40 * SCREENH6, 40 * SCREENH6)];
    
    //    addButton.backgroundColor = [UIColor clearColor];
    [addButton setImage:[UIImage imageNamed:@"加"] forState:UIControlStateNormal];
    [addButton addTarget:self action:@selector(didAddButton) forControlEvents:UIControlEventTouchUpInside];
    
    [textFiled addSubview:addButton];
    
    [self.addButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(textFiled);
        make.trailing.mas_equalTo(textFiled).offset(-7 * SCREENH6);
    }];
    
    textFiled.rightView = addButton;
    textFiled.rightViewMode = UITextFieldViewModeAlways;
    
    textFiled.keyboardType = UIKeyboardTypeDecimalPad;
    textFiled.keyboardAppearance = UIKeyboardAppearanceDark;
    
    
    return textFiled;
}


//点击减号
- (void)didReduceButton{

    CGFloat textCount = [self.pendingTextField.text floatValue];
    
    
    if ( textCount > 0.01) {
        
        float traderCount = textCount - 0.01;
        
        NSString * showString = [NSString stringWithFormat:@"%.2f",traderCount];
        
        self.pendingTextField.text = showString;
        
        float ensure = traderCount * 250;
        
        self.homeView.ensureString = [NSString stringWithFormat:@"%.2f",ensure];
        
    }else{
        
        self.pendingTextField.text = @"0.01";
        
        self.homeView.ensureString = @"2.50";
    }

    
}


//点击加号
- (void)didAddButton{
    
    float textCount = [self.pendingTextField.text floatValue];
    
    float traderCount = textCount + 0.01;
    
    NSString * showString = [NSString stringWithFormat:@"%.2f",traderCount];
    
    self.pendingTextField.text = showString;
    
    float ensure = traderCount * 250;
    
    self.homeView.ensureString = [NSString stringWithFormat:@"%.2f",ensure];
}


- (void)didShowLandscape{
    
    LandscapeViewController * landVC = [LandscapeViewController new];
    
    landVC.nameString = self.request;
    landVC.titleString = self.navigationItem.title;
    
    [self presentViewController:landVC animated:YES completion:nil];
}


- (void)pushToPendingVC{
    
    if (self.userID) {
        
        self.hidesBottomBarWhenPushed = YES;
        PendingOrderController * pendingVC = [PendingOrderController new];
        
        pendingVC.nowPrice = self.sellCountLabel.text;
        pendingVC.productID = self.request;
        
        [self.navigationController pushViewController:pendingVC animated:YES];
        
        self.hidesBottomBarWhenPushed = NO;
    }else{
        
        AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        
        BlackNavViewController * navVC = [[BlackNavViewController alloc] initWithRootViewController:[LoginViewController new]];
        
        appDelegate.window.rootViewController = navVC;
    }
    
}



//点击快捷买跌
- (void)tapSellAction{
    //buy,limit   买涨    buy,stop   买跌
    
    if (self.userID ) {
        
        if ([self.sellCountLabel.text isEqualToString:@""]) {
            
        }else{
            [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            
//            float textCount = [self.pendingTextField.text floatValue];
//            
//            int trderCount = 100 * textCount;
//            
//            NSString * trderString = [NSString stringWithFormat:@"%d",trderCount];
            //@"buy,stop",@"orderPrice":self.sellCountLabel.text
            NSDictionary * parameters = @{@"symbol":self.request,@"volume":self.pendingTextField.text,@"orderType":@"sell"};
            
            [[NetworkTool sharedTools] POST:@"symbols/buy-or-sell" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
                
                NSString * code = [NSString stringWithFormat:@"%@",responseObject[@"code"]];
                
                if ([code isEqualToString:@"0"]) {
                    
                    [MBProgressHUD hideHUDForView:self.view animated:YES];
                    
                    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                                   message:@"恭喜你，交易成功！"
                                                                            preferredStyle:UIAlertControllerStyleAlert];
                    
                    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                          handler:^(UIAlertAction * action) {
                                                                              //响应事件
//                                                                              [self loadData];
//                                                                              [self setupUI];
//                                                                              [self loadTopView];
//                                                                              [self loadTopViewData];
                                                                              self.hidesBottomBarWhenPushed = YES;
                                                            
                                                                              OrderViewController * orderVC = [OrderViewController new];
                                                                              
                                                                              [self.navigationController pushViewController:orderVC animated:YES];
                                                                              
                                                                              
                                                                              self.hidesBottomBarWhenPushed = NO;
                                                                              
                                                                          }];
                    
                    [alert addAction:defaultAction];
                    [self presentViewController:alert animated:YES completion:nil];
                    
                }else{
                    
                    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                                   message:responseObject[@"msg"]
                                                                            preferredStyle:UIAlertControllerStyleAlert];
                    
                    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                          handler:^(UIAlertAction * action) {
                                                                              //响应事件
                                                                              [self loadData];
                                                                              [self setupUI];
                                                                          }];
                    
                    [alert addAction:defaultAction];
                    [self presentViewController:alert animated:YES completion:nil];
                }
                
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
                NSLog(@"%@",error);
                
                [MBProgressHUD hideHUDForView:self.view animated:YES];
                
                UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                               message:@"网络连接错误。"
                                                                        preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                      handler:^(UIAlertAction * action) {
                                                                          //响应事件
                                                                          [self loadData];
                                                                          [self setupUI];
                                                                      }];
                
                [alert addAction:defaultAction];
                [self presentViewController:alert animated:YES completion:nil];
                
            }];
        }
        
        }else{
        
        AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        
        BlackNavViewController * navVC = [[BlackNavViewController alloc] initWithRootViewController:[LoginViewController new]];
        
        appDelegate.window.rootViewController = navVC;
    }
    
}

//点击快捷买涨
- (void)tapBuyAction{
    
    if (self.userID) {
        
        if ([self.buyCountLabel.text isEqualToString:@""]) {
            
        }else{
            
            [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            
//            float textCount = [self.pendingTextField.text floatValue];
//            
//            int trderCount = 100 * textCount;
//            
//            NSString * trderString = [NSString stringWithFormat:@"%d",trderCount];
            //@"buy,limit",@"orderPrice":self.sellCountLabel.text
            NSDictionary * parameters = @{@"symbol":self.request,@"volume":self.pendingTextField.text,@"orderType":@"buy"};
            
            [[NetworkTool sharedTools] POST:@"symbols/buy-or-sell" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
                
                [MBProgressHUD hideHUDForView:self.view animated:YES];
                
                NSString * code = [NSString stringWithFormat:@"%@",responseObject[@"code"]];
                
                if ([code isEqualToString:@"0"]) {
                    
                    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                                   message:@"恭喜你，交易成功！"
                                                                            preferredStyle:UIAlertControllerStyleAlert];
                    
                    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                          handler:^(UIAlertAction * action) {
                                                                              //响应事件
//                                                                              [self loadData];
//                                                                              [self setupUI];
//                                                                              [self loadTopView];
//                                                                               [self loadTopViewData];
                                                                              self.hidesBottomBarWhenPushed = YES;
                                                                              
                                                                              OrderViewController * orderVC = [OrderViewController new];
                                                                              
                                                                              [self.navigationController pushViewController:orderVC animated:YES];
                                                                              
                                                                              
                                                                              self.hidesBottomBarWhenPushed = NO;
                                                                          }];
                    
                    [alert addAction:defaultAction];
                    [self presentViewController:alert animated:YES completion:nil];
                    
                }else{
                    
                    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                                   message:responseObject[@"msg"]
                                                                            preferredStyle:UIAlertControllerStyleAlert];
                    
                    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                          handler:^(UIAlertAction * action) {
                                                                              //响应事件
                                                                              [self loadData];
                                                                              [self setupUI];
                                                                          }];
                    
                    [alert addAction:defaultAction];
                    [self presentViewController:alert animated:YES completion:nil];
                }
                
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
                NSLog(@"%@",error);
                [MBProgressHUD hideHUDForView:self.view animated:YES];
                
                UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                               message:@"网络连接错误。"
                                                                        preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                      handler:^(UIAlertAction * action) {
                                                                          //响应事件
                                                                          [self loadData];
                                                                          [self setupUI];
                                                                      }];
                
                [alert addAction:defaultAction];
                [self presentViewController:alert animated:YES completion:nil];
                
            }]; 
        }
        
        }else{
        
        AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        
        BlackNavViewController * navVC = [[BlackNavViewController alloc] initWithRootViewController:[LoginViewController new]];
        
        appDelegate.window.rootViewController = navVC;
    }

}


- (void)didWatchHistoryOrder{
    
    if (self.userID) {
    
    self.hidesBottomBarWhenPushed = YES;
    
//    HistoryOrderViewController * historyVC = [HistoryOrderViewController new];
//    
//    [self.navigationController pushViewController:historyVC animated:YES];
        OrderViewController * orderVC = [OrderViewController new];
        
        [self.navigationController pushViewController:orderVC animated:YES];
        
    
     self.hidesBottomBarWhenPushed = NO;
    }else{
        
        AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        
        BlackNavViewController * navVC = [[BlackNavViewController alloc] initWithRootViewController:[LoginViewController new]];
        
        appDelegate.window.rootViewController = navVC;
    }
}


- (void)didShowRulesButton:(UIButton *)button{
    
    self.hidesBottomBarWhenPushed = YES;
    
    if ([button.titleLabel.text isEqualToString:@"查看详情"]) {
        
        OrderViewController * orderVC = [OrderViewController new];
        
        [self.navigationController pushViewController:orderVC animated:YES];
    }else{
        
        TransactionRulesViewController * rulesVC = [TransactionRulesViewController new];
        
        [self.navigationController pushViewController:rulesVC animated:YES];
    }
    
    
    self.hidesBottomBarWhenPushed = NO;
}


- (void)didRightImageButton:(NSNotification *)sender{
    
    self.hidesBottomBarWhenPushed = YES;
    
    NSString * buttonTagStr = [sender.userInfo objectForKey:@"buttonTag"];
    
    if ([buttonTagStr isEqualToString:@"1"]) {
        //入金
//        [[NetworkTool sharedTools] POST:@"user/bank-list" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
//            
//            NSDictionary * dict = responseObject[@"param"];
//            
//            if (dict.count == 0) {
//                self.hidesBottomBarWhenPushed = YES;
//                MoneyCardViewController * MoneyVC = [MoneyCardViewController new];
//                
//                [self.navigationController pushViewController:MoneyVC animated:YES];
//                self.hidesBottomBarWhenPushed = NO;
//            }else{
//                self.hidesBottomBarWhenPushed = YES;
//                PayViewController * payVC = [PayViewController new];
//                
//                [self.navigationController pushViewController:payVC animated:YES];
//                self.hidesBottomBarWhenPushed = NO;
//            }
//            
//        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//            
//            NSLog(@"%@",error);
//        }];
        
        self.hidesBottomBarWhenPushed = YES;
        PayViewController * payVC = [PayViewController new];
        
        [self.navigationController pushViewController:payVC animated:YES];
        self.hidesBottomBarWhenPushed = NO;
        
    }else{
        //平仓
//        if ([self.isPositions isEqualToString:@"0"]) {
//            //挂单
//            
//            PendingInfoViewController * pendingVC = [PendingInfoViewController new];
//            
//            pendingVC.orderId = self.orderId;
//            
//            [self.navigationController pushViewController:pendingVC animated:YES];
//        }else{
//            
//            OrderInfoViewController * orderInfoVC = [OrderInfoViewController new];
//            
//            orderInfoVC.positionId = self.positionId;
//            
//            [self.navigationController pushViewController:orderInfoVC animated:YES];
//        }
        
        OrderViewController * orderVC = [OrderViewController new];
        
        [self.navigationController pushViewController:orderVC animated:YES];
    }
    
    self.hidesBottomBarWhenPushed = NO;
}


//点击未登录状态下的登录按钮
- (void)popToLoginVC{
    
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    
    BlackNavViewController * navVC = [[BlackNavViewController alloc] initWithRootViewController:[LoginViewController new]];
    
    appDelegate.window.rootViewController = navVC;
}


//点击未登录状态下的注册按钮
- (void)popToSetupVC{
    
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    
    BlackNavViewController * navVC = [[BlackNavViewController alloc] initWithRootViewController:[MessageVerifyViewController new]];
    
    appDelegate.window.rootViewController = navVC;
    
}


- (void)loadUserInfo{
    
    [self loadTopViewData];
}


- (NSString*)weekdayStringFromDate:(NSDate*)inputDate {
    
    NSArray *weekdays = [NSArray arrayWithObjects: [NSNull null], @"Sunday", @"周一", @"周二", @"周三", @"周四", @"周五", @"周六", nil];
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    
    NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"Asia/Shanghai"];
    
    [calendar setTimeZone: timeZone];
    
    NSCalendarUnit calendarUnit = NSCalendarUnitWeekday;
    
    NSDateComponents *theComponents = [calendar components:calendarUnit fromDate:inputDate];
    
    return [weekdays objectAtIndex:theComponents.weekday];
    
}

//键盘弹出后将视图向上移动
-(void)keyboardWillShow:(NSNotification *)note
{
    NSDictionary *info = [note userInfo];
    CGSize keyboardSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    //目标视图UITextField
    CGRect frame = self.pendingTextField.frame;
    int y = frame.origin.y + frame.size.height - (self.view.frame.size.height - keyboardSize.height);
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeView" context:nil];
    [UIView setAnimationDuration:animationDuration];
    if(y > 0)
    {
        self.view.frame = CGRectMake(0, -y, self.view.frame.size.width, self.view.frame.size.height);
    }
    [UIView commitAnimations];
}

//键盘隐藏后将视图恢复到原始状态
-(void)keyboardWillHide:(NSNotification *)note
{
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeView" context:nil];
    [UIView setAnimationDuration:animationDuration];
    self.view.frame =CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    [UIView commitAnimations];
    
    float trander = [self.pendingTextField.text floatValue];
    float ensure = trander * 250;
    
    self.homeView.ensureString = [NSString stringWithFormat:@"%.2f",ensure];
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [self.pendingTextField resignFirstResponder];
}


- (void)viewDidDisappear:(BOOL)animated{
    
    [_webSocketNumber close];
        
    [_countDownTimer invalidate];

    self.topView.hidden = YES;
}

-(void)dealloc{
//    NSLog(@"观察者销毁了");
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
